package com.sky.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.RedisConstant;
import com.sky.dto.CategoryDTO;
import com.sky.pojo.Category;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("admin/category")
@Slf4j
@Api(tags = "分类管理")
public class CategoryController {
    @Resource
    CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("page")
    @ApiOperation(value = "分页查询")
    public Result getByPage(String name, Integer page, Integer pageSize, Integer type){
        PageHelper.startPage(page, pageSize);

        // 执行查询
        List<Category> pages = categoryService.getByPage(name, page, pageSize, type);

        // 获取分页信息
        PageInfo<Category> pageInfo = new PageInfo<>(pages);
        Long total = pageInfo.getTotal();
        return Result.success(PageResult.builder().total(total).records(pages).build());
    }
    //修改分类
    @PutMapping
    @ApiOperation(value = "修改分类")
    public Result update(@RequestBody Category category){
       Integer row =  categoryService.update(category);
       if(row == 0){
           return Result.error("修改失败");

       }
        return Result.success(row);
    }
    //新增分类
    @PostMapping
    @ApiOperation(value = "新增分类")
    public Result save(@RequestBody CategoryDTO categoryDTO){
        Integer row =  categoryService.save(categoryDTO);
        if(row == 0){
            return Result.error("新增失败");
        }
        return Result.success(row);
    }
    //修改启用状态
    @PostMapping("/status/{status}")
    @ApiOperation(value = "修改启用状态")
    public Result setStatus(@PathVariable Integer status, Long id){
        Category category = Category.builder().status(status).id(id).build();
        Integer row =  categoryService.update(category);
        if(row == 0){
            return Result.error("修改失败");
        }

        return Result.success(row);
    }
    //删除分类
    @DeleteMapping
    @ApiOperation(value = "删除分类")
    public Result delete(Long id){
        Integer row =  categoryService.delete(id);
        if(row == 0){
            return Result.error("删除失败");
        }
        return Result.success(row);
    }
//根据类型查询分类
    @GetMapping("/list")
    @ApiOperation(value = "根据类型查询分类")
    public Result getByType(Integer type){
        List<Category> list = categoryService.getByType(type);
        return Result.success(list);
    }

}
